#include "BasicAreaChart.h"
#include "../../../../storage/Storage.h"
#include "../../../../storage/Series.h"
#include <stdexcept>
#include <QMessageBox>

namespace LightChart
{
    BasicAreaChart::BasicAreaChart(std::string title) : Chart(title), values(this), labels(this)//, contribution()
    {
	values.set_label(std::string("values"));
	labels.set_label(std::string("labels"));
	restoreGlobalSettings();
    }
    void BasicAreaChart::draw() {}
    void BasicAreaChart::showOptions() {}
    void BasicAreaChart::restoreGlobalSettings()
    {
	const GlobalChartSettings& globalSettings = GlobalChartSettings::get_instance();
	title = globalSettings.chartTitle;
	windowWidth = globalSettings.width;
	windowHeight = globalSettings.height;
	bgColor = globalSettings.bgColor;
    }
    std::vector<Axis*> BasicAreaChart::get_axes()
    {
	std::vector<Axis*> axes;
	axes.push_back(&values);
	axes.push_back(&labels);
	return axes;
    }
    const std::vector<unsigned short int>& BasicAreaChart::get_contribution()
    {
	try
	{
	    contribution.clear();
	    std::map<Axis*, std::vector<Series*> >& axes = Storage::get_instance().charts[this];
	    std::vector<Series*>& series_v = axes[&values];
	    if(series_v.size() > 1) throw std::runtime_error("Assigning more than one data series to the values' axis is pointless. Chart will be "
							     "plotted using only those data series that were assigned first.");
	    if(series_v.empty()) throw std::runtime_error("You have not assigned any data series to values' axis. Without this "
							  "the chart cannot be plotted. Please assign at least one numeric data series.");
	    Series* val = series_v.front();
	    if(val->get_type() == UNKNOWN || val->get_type() == S_TEXT)
		throw std::runtime_error("Data series assigned to values' axis must be numeric. Chart will not be plotted.");
	    const std::vector<double>& v = val->get_double_vector();
	    double sum = 0.;
	    for(const double& s : v) sum += s;
	    contribution.push_back(0);
	    for(unsigned i = 1; i < v.size() + 1; ++i) contribution.push_back(static_cast<unsigned short int>(v[i-1] * 100 / sum));
	}
	catch(const std::exception& e)
	{
	    QMessageBox::critical(0,"Error occured",e.what());
	}
	return contribution;
    }
}
